<?php
/**
 * Created by PhpStorm.
 * User: zeng
 * Date: 18-5-15
 * Time: 上午9:12
 */

namespace App\Http\Controllers;

use App\User;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Tymon\JWTAuth\Facades\JWTAuth;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $validator=\Validator::make($request->all(),[
            'name'  =>'required',
            'password' =>'required',
//            'vercode'=>'required'
        ],['required'=>':attribute不能为空'],['name'=>'账号','password'=>'手机号']);
        if($validator->fails()){
            return response()->json(['code'=>'1','msg'=>$validator->errors()->first(),'data'=>'']);
        }
        try {
            if (!$token = JWTAuth::attempt(['name'=>$request->input('name'),'password'=>$request->input('password')])) {
                return response()->json(['code'=>'1','msg' => '用户账号密码错误', 'data' => '']);
            }
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            return response()->json(['code'=>'1','msg' => 'token_invalid', 'data' => '']);
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            return response()->json(['code'=>'1','msg' => 'token_expired', 'data' =>'']);
        }
        return response()->json(['code'=>'0','msg' => '登陆成功', 'data' =>['access_token'=>$token]]);
    }
    public function vericode($id){
        $abc = rand(10000, 99999);
        $builder=new CaptchaBuilder("$abc");
        $builder->build();
        $phrase = $builder->getPhrase();
        Session::put('milkcaptcha', $phrase);
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
    }
    public function index(Request $request){
//        $abc = rand(10000, 99999);
//        $builder=new CaptchaBuilder("$abc");
//        $builder->build();
//        $phrase = $builder->getPhrase();
//        Session::put('', $phrase);
//        echo Session::get('milkcaptcha');
       echo $request->session()->get('validate_code');
    }
    public function getUserInfo()
    {
        try {
            $user = JWTAuth::toUser($_GET['access_token']);
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            return response()->json(['code'=>'1001','msg' => 'token_invalid', 'data' => '']);
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            return response()->json(['code'=>'1001','msg' => '登录过期,请重新登录', 'data' => '']);
        }
        return response()->json(['code'=>'0','msg'=>'ok','data'=>['name'=>$user->name]]);

    }
}